<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>套餐编辑</title>
	<meta name="renderer" content="webkit">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
	<meta name="apple-mobile-web-app-status-bar-style" content="black">
	<meta name="apple-mobile-web-app-capable" content="yes">
	<meta name="format-detection" content="telephone=no">
	<link rel="stylesheet" href="/plugins/layui/css/layui.css" media="all" />
	<link rel="stylesheet" href="/css/combo/combosAdd.css">
	<style>
		.table-select-icon{position:absolute;right:10px;line-height:34px;color:#d3d3d3}
		.table-select-selected dl{display:block}
		.table-select dl{position:absolute;left:0;padding:5px 0;z-index:999;min-width:100%;border:1px solid #d2d2d2;max-height:300px;
			overflow-y:auto;background-color:#fff;border-radius:2px;box-shadow:0 2px 4px rgba(0,0,0,.12);box-sizing:border-box}
		.table-select dl dd{cursor:pointer}
		.table-select dl dd,.table-select dl dt{padding:0 10px;line-height:36px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
		.table-select dl dd.layui-this{background-color:#5FB878;color:#fff}
		.table-select dl dd,.table-select dl dt{padding:0 10px;line-height:36px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
		.table-select dl dd:hover{background-color:#f2f2f2}

	</style>
</head>
<body class="childrenBody">
<div class="container">
	<div class="header">
		<h3>添加套餐</h3>
	</div>
	<div class="item-msg">
		<h3>温馨提示</h3>
		<p>1.若项目勾选了不限，则该套餐售出后，客户消费该项目时不受数量限制。例：普通洗车项目为20次，勾选【不限】后，客户购买消费时则不再受数量限制，
			全年均可消费任何次数的普通洗车服务。</p>
		<p>2.套餐单价的计算：套餐合计价除以套餐数量，得出套餐单价</p>
		<p>3.消费计算：消费时，在设置数量范围内，预收款平摊到车主的消费中，若超出了数量，预收款已经用完，则消费价格为0</p>
	</div>
	<div class="item-list">
		<div class="item-header">
			<ul>
				<li class="state">
					<p>套餐状态：</p>
					<div class="layui-form">
						<input type="radio" name="status" title="有效" value="1">
						<div class="layui-unselect layui-form-radio">
							<i class="layui-anim layui-icon"></i>
							<div>有效</div>
						</div>
						<input type="radio" name="status" title="停用" value="0">
						<div class="layui-unselect layui-form-radio layui-form-radioed">
							<i class="layui-anim layui-icon layui-anim-scaleSpring"></i>
							<div>停用</div>
						</div>
					</div>
				</li>
			</ul>
			<ul>
				<li class="state">
					<p>套餐名称：</p>
					<input type="text" placeholder="请输入套餐名称" class="p-name" id="comboName">
				</li>
				<li>
					<p>有效期：</p>
					<div class="layui-inline">
						<input type="text" placeholder="请输入套餐有效期" id="comboUsePeriod" class="p-name" >月

					</div>
				</li>
				<li>
					<em>售价：</em><em class="price_number">0</em><em>元</em>
				</li>
			</ul>
		</div>
		<div class="table-list">
			<table class="layui-table" id="datademo" lay-filter="datademo">

			</table>
		</div>
		<div class="footer-add">
			<span id="addItem">添加项目</span>
		</div>
	</div>
</div>
<div class="footer-item">
	<span class="save" id="submitButton">保存</span>
	<span class="firm">取消</span>
</div>
<div class="tabbackgroud">
	<div class="choose-item">
		<div class="item-table-list">
			<table class="layui-table" id="tabdemo" lay-filter="tabdemo">
			</table>
		</div>

		<div class="footer-sitem">
			<button class="layui-btn save-item">保存</button>
			<button class="layui-btn choose-sitem">取消</button>
		</div>
	</div>
</div>
<script type="text/javascript" src="/js/jquery-1.11.2.min.js"></script>
<script type="text/javascript" src="/plugins/layui/layui.js"></script>
<!-- 	<script type="text/javascript" src="/js/user/newsAdd.js"></script> -->
<script type="text/html" id="selectTpl_type">
	{{d.type}}<i class="layui-icon table-select-icon"></i>
</script>
<script type="text/html" id="delDemo">
	<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<script id="itemSelect" type="text/html">
	<select name="" id="">
		<option value="1">请选择</option>
		<option value="2">2</option>
		<option value="3">3</option>
	</select>
</script>
<!--价格模板-->
<script id="itemPrice" type="text/html">
	<input type="text" value={{d.price2===''?'0':d.price2}} class="item-s-price price price-input">
	<span style="margin:6px 10px 0 10px;display: inline-block;">元</span>
</script>
<!--数量模板-->
<script id="itemNumber" type="text/html">
	<input type="text" class="item-s-price pricenumber num-input"  value={{d.count===''?'1':d.count}}>
	<div style="float:left;margin:6px 10px;">
		<input type="checkbox" name="zzz" lay-skin="switch" lay-text="限制|不限">
	</div>

</script>
<script type="text/javascript">
    var tabledata = [];   //弹出的产品选择列表
    var chooseTabledata=[];  //选中的产品列表
    layui.config({
        base: '/js/admin/'
    }).extend({
        ajaxExtention: 'ajaxExtention',
        $tool: 'tool'
    }).use(['form','layer','jquery','table','$tool'],function(){
        var form = layui.form,
            layer = parent.layer === undefined ? layui.layer : parent.layer,
            $ = layui.jquery,
			$tool=layui.$tool,
            table=layui.table;

        var queryArgs = $tool.getQueryParam();//获取查询参数
        var id = queryArgs['id'];
        function getIndexInChooseTable(productId){
            for(var i=0;i<chooseTabledata.length;i++){
                if(chooseTabledata[i].productId==productId){
                    return i;
                }
			}
		}

        function getIndexInTable(productId){
            console.log(tableList);
            for(var i=0;i<tableList.length;i++){
                if(tableList[i].productId==productId){
                    return i;
                }
            }
		}
        initCombo();
        function initCombo(){
            $.ajax({
                type : "GET",
                url: '/combos/get/'+id,
				async:false,
                success: function(data){
                    if(data.code==2000){
                       var master=data.data.comboMaster;
                       var detailList=data.data.comboDetailList;
                       $("#comboName").val(master.name);
                       $("#comboUsePeriod").val(master.usePeriod);
                       $(":radio[name='status'][value='" + master.status + "']").prop("checked", "checked");

						for (var i in detailList){
						    var obj={};
						    obj.id=detailList[i].id;
						    obj.productId=detailList[i].productId;
						    obj.name=detailList[i].productName;
                            obj.price=detailList[i].productUnitPrice;
                            obj.price2=detailList[i].comboUnitPrice;
                            obj.count=detailList[i].quantity;
                            chooseTabledata.push(obj);
						}

                        table.reload('datademo',{
                            data : chooseTabledata
                        });

                        var Money  = 0;
                        for(var i in chooseTabledata){
                            if(chooseTabledata[i].price2 == undefined){
                                Money  =Money  + parseFloat(chooseTabledata[i].price) * parseInt(chooseTabledata[i].count);
                            }else{
                                Money  =Money  + parseFloat(chooseTabledata[i].price2) * parseInt(chooseTabledata[i].count);
                            }
                        }
                        $(".price_number").html(Money);
                      	 form.render();

                    }
                }
            });

		}
        //初始化选中的产品列表
        table.render({
            elem: '#datademo'
            , data: chooseTabledata
            , page: false
            , cols: [[
                {field: 'name', title: '套餐项目',width:"20%"}
                , {field: 'price', title: '原价',width:"10%"}
                , {field: 'price2', title: '套餐单价(元)',width:"15%"}
                , {field: 'count', title: '数量(件)',width:"15%"}
                , {title: '操作', align: 'center', toolbar: '#delDemo'}
            ]],
            limit:100
        });
        table.on('tool(datademo)', function(obj){
            var data = obj.data //获得当前行数据
                ,layEvent = obj.event;
            console.log(chooseTabledata)
            if(layEvent === 'del'){
                layer.confirm('真的删除行么', function(index){
                    obj.del();
                    layer.close(index);
                    for(var i in chooseTabledata){
                        if(chooseTabledata[i].productId ==obj.data.productId){
                            chooseTabledata.splice(i,1);
                            tableList[getIndexInTable(obj.data.productId)].LAY_CHECKED=false;
                        }
                    }
                    table.reload("tabdemo",{
                        data:tableList
                    })
                });
            }
        });

        //监听单元格编辑
        table.on('edit(tabdemo)', function(obj){
            var value = obj.value //得到修改后的值
                ,data = obj.data //得到所在行所有键值
                ,field = obj.field; //得到字段
            console.log(data);
        });


        //异步获取产品列表数据，并初始化已经选中的数据
		var tableList=[]
        $.ajax({
            url:'/products/products.json',
            method:"GET",
            async:false,
            success:function (data) {
                data.data.forEach(function (t) {
                    if(getIndexInChooseTable(t.id)!=undefined){
                        t.LAY_CHECKED=true;
                        t.productId=t.id;
                        t.price2=chooseTabledata[getIndexInChooseTable(t.id)].price2;
                        t.count=chooseTabledata[getIndexInChooseTable(t.id)].count;
					}else{
                        t.productId=t.id;
                        t.price2=t.price;
                        t.count=0;
					}

                })
                tableList=data.data;
            }
        });

        table.on('checkbox(tabdemo)', function(obj){
            if(obj.checked){
                if(obj.type ==="all"){
                    chooseTabledata=[];
                    for(var i in tableList){
                        tableList[i].productId=obj.data.id;
                        obj.data.id=0;//用来标记删除
                        chooseTabledata.push(tableList[i])
                    }
                }else{
                    obj.data.productId=obj.data.id;
                    obj.data.id=0;//用来标记删除
                    chooseTabledata.push(obj.data)
                }
            }else{
                if(obj.type ==="all"){
                    for(var i in tableList){
                        chooseTabledata.splice(chooseTabledata[i],1);
                    }
                }else{

                    for(var i in chooseTabledata){
                        if(chooseTabledata[i].productId ==obj.data.id){
                            chooseTabledata.splice(i,1);
                        }
                    }
                }
            }
        });
        table.render({
            elem: '#tabdemo'
            , data: tableList
            , page: false
            ,width:980
            , cols: [[
                {checkbox: true,width:"10%"}
                ,{field: 'name', title: '套餐项目',width:"30%"}
                , {field: 'price', title: '原价(元)',width:"20%"}
                , {field: 'price2', title: '套餐单价(元)',width:"20%",edit:'number'}
                , {field: 'count', title: '数量(件)',width:"20%",edit:'number'}
            ]],
            limit:100
        });


        $(".choose-sitem").click(()=>{
            $(".tabbackgroud").css("display","none");
   		 })

        $(".save-item").click(()=>{
            var Money  = 0;
			for(var i in chooseTabledata){
				if(chooseTabledata[i].price2 == undefined){
					Money  =Money  + parseFloat(chooseTabledata[i].price) * parseInt(chooseTabledata[i].count);
				}else{
					Money  =Money  + parseFloat(chooseTabledata[i].price2) * parseInt(chooseTabledata[i].count);
				}

				layer.msg(chooseTabledata[i].count);
				if(parseInt(chooseTabledata[i].count)<1){
					return layer.msg("填写数量必须大于等于1")
				}
			}
			$(".price_number").html(Money);
			table.reload('datademo',{
				data : chooseTabledata
			});
			$(".tabbackgroud").css("display","none");
    	})


        $("#addItem").click(()=>{
            $(".tabbackgroud").css("display","block");
        	$(".container").css("overflow-y","hidden")
   		 })


        $("#submitButton").click(function () {
            if($("#comboName").val()==''){
                layer.msg('请填写套餐名称');
                return;
            }
            if($("#comboUsePeriod").val()==''){
                layer.msg('请填写有效期');
                return;
            }
            if(chooseTabledata.length==0){
                layer.msg('请添加服务项目');
                return;
            }
            var master={};
            var detailList=[];
            chooseTabledata.forEach(function(e){
                console.log(e);
                var temp={};
                temp.productId=e.productId;
                temp.comboUnitPrice=parseFloat(e.price2);
                temp.productUnitPrice=parseFloat(e.price);
                temp.quantity=e.count;
                detailList.push(temp);
            });

            var status=$(':radio[name="status"]:checked').val();
            var obj={};
            master.id=id;
            master.status=status;
            master.usePeriod=$("#comboUsePeriod").val();
            master.name=$("#comboName").val();
            master.price=$(".price_number").text();
            obj.comboMaster=master;
            obj.comboDetailList=detailList;
            var index = top.layer.msg('数据提交中，请稍候',{icon: 16,time:false,shade:0.8});
            $.ajax({
                url:'/combos',
                method:"PUT",
                data:JSON.stringify(obj),
                contentType:"application/json",
                success:function (data) {
                    if(data.code==2000){
                        top.layer.close(index);
                        top.layer.msg("添加成功！");
                        layer.closeAll("iframe");
                        //刷新父页面
                        parent.location.reload();
                    }else{
                        top.layer.msg(data.msg);
                    }
                }

            });
        });


    ////////
    })



</script>
</body>
</html>

